using System;
using System.Collections.Generic;
using Godot;

public interface IRegistable
{
    int Index { get; set; }
}

public class Registry<K, V>
    where V: IRegistable
{
    private Dictionary<K, int> _indices;
    private List<V> _entries;
    public Registry()
    {
        _indices = new Dictionary<K, int>();
        _entries = new List<V>();
    }

    public bool Empty => _entries.Count == 0;

    public void AddEntry(K id, V entry)
    {
        var index = _entries.Count;
        entry.Index = index;
        _indices.Add(id, index);
        _entries.Add(entry);
    }

    public void Clear()
    {
        _indices.Clear();
        _entries.Clear();
    }

    public V GetEntry(int index)
    {
        if (index >= 0 && index < _entries.Count)
            return _entries[index];
        return default;
    }

    public V GetEntryById(K id) => _indices.TryGetValue(id, out int index) ? GetEntry(index) : default;

    public int? GetIndex(K id) => _indices.TryGetValue(id, out int index) ? index : null;

    public K GetId(int index)
    {
        foreach (var (key, value) in _indices)
        {
            if (value == index)
                return key;
        }
        return default;
    }

    public void PrintLoadList(Action<string> print)
    {
        foreach (var (key, value) in _indices)
            print($"{key}:{_entries[value]}");
    }
}